package com.chinacreator.galaxylive.web.rest;


import com.chinacreator.c2.config.ConfigManager;
import com.chinacreator.galaxylive.bean.UserBean;
import com.chinacreator.galaxylive.service.PageService;
import com.chinacreator.galaxylive.wx.WxService;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 页面信息获取
 */
@Path("/page/")
@Produces({MediaType.APPLICATION_JSON })
@Consumes({MediaType.APPLICATION_JSON })
@Controller
public class PageResource {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WxService wxService;

    @Autowired
    private PageService pageService;


    @Context
    private HttpServletRequest request;
    @Context
    private HttpServletResponse response;


    @GET
    @Path("/index")
    public Map getIndexData(@QueryParam("url") String url){
        Map<String,Object> outMap = new HashMap<>();
        UserBean userBean = pageService.getUserBean();
        if(userBean != null){
            outMap.put("userId",userBean.getMemberId());
            try {
                WxJsapiSignature wxJsapiSignature = wxService.createJsapiSignature(url);
                outMap.put("jsapiSignature",wxJsapiSignature);
            } catch (WxErrorException e) {
                logger.error("创建调用jsapi时所需要的签名,失败",e);
            }
        }else {
            //TODO 获取用户信息失败
        }
        return outMap;
    }


    @GET
    @Path("/detail")
    public Map getdetailData(@QueryParam("url") String url){
        Map<String,Object> outMap = new HashMap<>();
        UserBean userBean = pageService.getUserBean();
        if(userBean != null){
            outMap.put("userId",userBean.getMemberId());
            outMap.put("userName",userBean.getName());
            outMap.put("userImg",userBean.getAvatar());
            outMap.put("mqttUrl", ConfigManager.getInstance().getConfig("live.mqttUrl"));
            outMap.put("appId",wxService.getWxMpConfigStorage().getAppId());
            try {
                WxJsapiSignature wxJsapiSignature = wxService.createJsapiSignature(url);
                outMap.put("jsapiSignature",wxJsapiSignature);
            } catch (WxErrorException e) {
                logger.error("创建调用jsapi时所需要的签名,失败",e);
            }
        }else {
            //TODO 获取用户信息失败
        }
        return outMap;
    }
}
